package com.hs.dnms.action.produce;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hs.auth.model.HsAccount;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.GlobalParamCache;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.core.utils.SystemUtil;
import com.hs.core.utils.TimeUtil;
import com.hs.core.utils.Tools;
import com.hs.core.utils.UUIDGenerator;
import com.hs.dnms.model.DnmsBook;
import com.hs.dnms.model.DnmsDisease;
import com.hs.dnms.model.DnmsFile;
import com.hs.dnms.service.IDataService;
 @Controller  
public class DataProController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(DataProController.class);
	private IDataService dataService;
	@Autowired  
	public void setDataService(IDataService dataService) {
		this.dataService = dataService;
	}
	 /**
	  * 数据加工主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping("/produce/datafinishlist.do")   
     public ModelAndView datafinishlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		    PageParam pageParam = new  PageParam(request,"produce/datafinishlist.do");
			StringBuffer buffer = new StringBuffer();

//		  /** 排序部分*/
			StringBuffer orderByStr = new StringBuffer(" ");
			//	//排序部分
			String orderName = request.getParameter("orderName");
			String orderNum = request.getParameter("orderNum"); 
			String bookname = request.getParameter("bookname");
			String nianfen = request.getParameter("nianfen"); 
			 if(StringUtils.isNotBlank(orderName)){
			    	if("1".equals(orderNum)){
			    		orderByStr.append(orderName).append(" asc");
			    	}
			    	if("2".equals(orderNum)){
			    		orderByStr.append(orderName).append(" desc");
			    	}
			    }else{
			    	orderByStr.append("a.publishdate").append(" desc");
			    	orderName = "a.publishdate";
			    	orderNum = "2";
			    }
			 request.setAttribute("orderName", orderName); 
			 request.setAttribute("orderNum", orderNum); 
			 pageParam.getConditionMap().put("orderName", orderName);
			 pageParam.getConditionMap().put("orderNum", orderNum);
			 HsAccount accinfo = this.getCurrentuser(request);
			 /** 排序部分*/
		    //排序结束
			PageUtil pageUtil = null;
			StringBuffer searchBuffer = new StringBuffer(" select a from DnmsBook a  where a.dataproducer.id =").append(accinfo.getId());
			String prename = request.getParameter("prename"); 
			String precomfrom = request.getParameter("precomfrom"); 
			 
			if(StringUtils.isNotBlank(bookname)){
				searchBuffer.append(" and (a.bookname like '%").append(bookname).append("%') ");
				pageParam.getConditionMap().put("bookname", bookname);
				request.setAttribute("bookname", bookname);
			}  
			if(StringUtils.isNotBlank(nianfen)){
				searchBuffer.append(" and a.publishdate like'%").append(nianfen).append("%'");
				pageParam.getConditionMap().put("publishdate", nianfen);
				request.setAttribute("nianfen", nianfen);
			}  
			searchBuffer.append(" ORDER BY   ").append(" a.state");
			Map data = new HashMap();
 
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = dataService.getPageList(pageParam); 
			modelMap.put("prodatalist", pageUtil);  
 		 return new ModelAndView("app/produce/finishdatalist",modelMap);
		 
	 } 
	 /**
	  * 图片上传主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/uploadFile.do", method = RequestMethod.GET)   
     public ModelAndView uploadFile(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
         String id = request.getParameter("id");
         DnmsBook obj = (DnmsBook)dataService.findByID(DnmsBook.class, new Long(id));
         modelMap.put("obj", obj);
		 return new ModelAndView("app/produce/fileUpload",modelMap);
		 
	 }
	 /**
	  * 数据加工主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping("/produce/dataprolist.do")   
     public ModelAndView waitProlist(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		    PageParam pageParam = new  PageParam(request,"produce/dataprolist.do");
			StringBuffer buffer = new StringBuffer();

//		  /** 排序部分*/
			StringBuffer orderByStr = new StringBuffer(" ");
			//	//排序部分
			String orderName = request.getParameter("orderName");
			String orderNum = request.getParameter("orderNum"); 
			String bookname = request.getParameter("bookname");
			String nianfen = request.getParameter("nianfen"); 
			 if(StringUtils.isNotBlank(orderName)){
			    	if("1".equals(orderNum)){
			    		orderByStr.append(orderName).append(" asc");
			    	}
			    	if("2".equals(orderNum)){
			    		orderByStr.append(orderName).append(" desc");
			    	}
			    }else{
			    	orderByStr.append("a.publishdate").append(" desc");
			    	orderName = "a.publishdate";
			    	orderNum = "2";
			    }
			 request.setAttribute("orderName", orderName); 
			 request.setAttribute("orderNum", orderNum); 
			 pageParam.getConditionMap().put("orderName", orderName);
			 pageParam.getConditionMap().put("orderNum", orderNum);
			 /** 排序部分*/
		    //排序结束
			PageUtil pageUtil = null;
			StringBuffer searchBuffer = new StringBuffer(" select a from DnmsBook a  where a.state in('0','4') and a.dataproducer is null ");
			 
			 
			if(StringUtils.isNotBlank(bookname)){
				searchBuffer.append(" and (a.bookname like '%").append(bookname).append("%' )");
				pageParam.getConditionMap().put("bookname", bookname);
				request.setAttribute("bookname", bookname);
			}  
			if(StringUtils.isNotBlank(nianfen)){
				searchBuffer.append(" and a.publishdate like '%").append(nianfen).append("%'");
				pageParam.getConditionMap().put("nianfen", nianfen);
				request.setAttribute("nianfen", nianfen);
			}  
			searchBuffer.append(" ORDER BY   ").append(orderByStr);
			Map data = new HashMap();
 
			pageParam.setSearchSql(searchBuffer.toString());
			pageUtil = dataService.getPageList(pageParam); 
			modelMap.put("prodatalist", pageUtil);  
 		 return new ModelAndView("app/produce/datalist",modelMap);
		 
	 } 
	 /**
	  * 数据加工页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dataPro.do", method = RequestMethod.GET)   
     public ModelAndView dataPro(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String id = request.getParameter("id");
		 DnmsBook obj = (DnmsBook)this.dataService.findByID(DnmsBook.class, new Long(id));
		 HsAccount accinfo = this.getCurrentuser(request);
		 if(null != accinfo){
			 Long accid = accinfo.getId();
			 this.getDbo(request).update("update DNMS_BOOK set DATAPRODUCER=?,STATE='1' where id=?", new Object[]{accid,obj.getId()});
		 }
		 modelMap.put("obj", obj);
		 return new ModelAndView("app/produce/dataframe",modelMap);
		 
	 }
	 /**
	  * 文件加工页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/datafilePro.do", method = RequestMethod.GET)   
     public ModelAndView datafilePro(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String id = request.getParameter("id");
		 DnmsBook obj = (DnmsBook)this.dataService.findByID(DnmsBook.class, new Long(id));
		 modelMap.put("obj", obj);
		 String  tempsql = "select id,distype,disname from DNMS_MODERN_DIS where validsign='1'";
         List modlist = DBMgr.getDbUtilInst().queryList(tempsql,null);
         System.out.println("poiList.size()::::" + modlist.size());
         modelMap.put("modlist", modlist);
		 return new ModelAndView("app/produce/dataPro",modelMap);
		 
	 }
	 /**
	  * 结构化数据主页面
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/datamain.do", method = RequestMethod.GET)   
     public ModelAndView datamain(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String id = request.getParameter("id");
		 String disid = request.getParameter("disid");
		 String sid = "" ;
		 if(StringUtils.isEmpty(disid)){
//        	 DnmsBook obj = (DnmsBook)this.dataService.findByID(DnmsBook.class, new Long(id));
//             Set disset = obj.getDisset();
//             Iterator iter = disset.iterator();
//             while(iter.hasNext()){
//            	 DnmsDisease dis = (DnmsDisease)iter.next();
//            	 disid = dis.getId()+"";
//            	 sid = sid + disid + "," ;
//             }
         }
		 System.out.println("disid::::::::" + disid + "::::sid:::::::::::" + sid);
		 modelMap.put("id", id);
		 modelMap.put("disid", disid);

		// DnmsMagazine obj = (DnmsMagazine)this.dataService.findByID(DnmsMagazine.class, new Long(id));
 		 return new ModelAndView("app/produce/dataPromain",modelMap);
		 
	 }
	 /**
	  * 疾病加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/disdata.do", method = RequestMethod.GET)   
     public ModelAndView disdata(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String disid = request.getParameter("disid");
		 String id = request.getParameter("id");
         if(StringUtils.isEmpty(disid)){
//        	 DnmsBook obj = (DnmsBook)this.dataService.findByID(DnmsBook.class, new Long(id));
//             Set disset = obj.getDisset();
//             Iterator iter = disset.iterator();
//             while(iter.hasNext()){
//            	 DnmsDisease dis = (DnmsDisease)iter.next();
//            	 disid = dis.getId()+"";
//             }
         }
 		 modelMap.put("disid", disid);
 		 modelMap.put("id", id);
		 return new ModelAndView("app/produce/disinfo",modelMap);
		 
	 }
	 
	 /**
	  * 证候信息加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dissymdata.do", method = RequestMethod.GET)   
     public ModelAndView dissymdata(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String disid = request.getParameter("disid"); 
		 String bookid = request.getParameter("id"); 
		 if(!"null".equals(disid) && StringUtils.isNotEmpty(disid)){
        	 DnmsDisease disobj = (DnmsDisease)this.dataService.findByID(DnmsDisease.class, new Long(disid));
    		 modelMap.put("disobj", disobj); 
         }else if(!"null".equals(bookid) && StringUtils.isNotEmpty(bookid)){
        	 String hql = "select a from DnmsDisease a where a.bookid=" + bookid;
        	 List disobjList = this.dataService.findList(hql);
    		 modelMap.put("disobjList", disobjList); 
         }
		 return new ModelAndView("app/produce/dissyminfo",modelMap);
		 
	 }
	 
	 /**
	  * 穴位信息加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/produce/dispointdata.do", method = RequestMethod.GET)   
     public ModelAndView dispointdata(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 String disid = request.getParameter("disid"); 
		 String bookid = request.getParameter("id");  
		 if(!"null".equals(disid) && StringUtils.isNotEmpty(disid)){
        	 DnmsDisease disobj = (DnmsDisease)this.dataService.findByID(DnmsDisease.class, new Long(disid));
    		 modelMap.put("disobj", disobj); 
         }else if(!"null".equals(bookid) && StringUtils.isNotEmpty(bookid)){
        	 String hql = "select a from DnmsDisease a where a.bookid=" + bookid;
        	 List disobjList = this.dataService.findList(hql);
    		 modelMap.put("disobjList", disobjList); 
         } 
		 return new ModelAndView("app/produce/dispointinfo",modelMap);
		 
	 }
	 /**
	  * 原文加工
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping("/produce/fileSave.do")   
     public void fileSave(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws Exception {
		    logger.debug("enter");
			String id = request.getParameter("id");
			String newsign = (String)request.getParameter("newsign");
			System.out.println("newsign:" + newsign);
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
			MultipartFile multipartFile = multipartRequest.getFile("bookfile");   
			String fileName = multipartFile.getOriginalFilename();  
 			HsAccount accobj = this.getCurrentuser(request);
			String[] bookinfo = this.writePdfFile(multipartFile.getBytes(), fileName);
 			//对于没有后缀名的文件，忽略不处理 
			DnmsFile fileobj = null;
			String returnId = "";
 			fileobj = new DnmsFile();
 			fileobj.setNewsign(newsign);
			fileobj.setFilename(fileName);
			fileobj.setBookid(new Long(id));
			fileobj.setUserid(accobj == null?0:accobj.getId());
			fileobj.setUploaddate(TimeUtil.getCurrentstr());
 			fileobj.setFilepath(bookinfo[0]+bookinfo[1]);
			this.dataService.saveObject(fileobj);
			returnId = fileobj.getId() +"";
			response.setCharacterEncoding("UTF-8");
			StringBuffer buffer =  new StringBuffer();
			buffer.append(returnId).append("$").append("[{"); 
			buffer.append("id:'").append(returnId).append("',"); 
			buffer.append("url:'").append(fileobj.getFilepath()).append("',");  
			buffer.append("fileName:'").append(fileobj.getFilename()).append("'");
			buffer.append("}]"); 		 
	    	try {
				PrintWriter w = response.getWriter(); 
				 w.println(buffer.toString());
				 w.flush();
				 w.close();
			} catch (IOException e) {
				 throw e;
			} 
 		 
	 }
	 
	 private String[] writePdfFile(byte[] fileContent,String fileName) throws Exception{
			String[] temp = new String[3];
			StringBuffer buffer = new StringBuffer();
			String sep = System.getProperty("file.separator");
			sep = "/"; 
			//存储路径
			//String webRoot = GlobalParamCache.getInst().getParamByKey("filepath");// SystemUtil.getWebappRoot().getPath() + sep +  "upload";//SWFConvertUtil.getParamMap("filepath");// 
			String webRoot = GlobalParamCache.getInst().getParamByKey("dnmsabfile");
			System.out.println("webroot::::" + webRoot);
			//String webRoot = SystemUtil.getWebappRoot().toString();
			//webRoot = webRoot.replace("\\", "/") + "/temp";
			String middlePath = Tools.buildFileSubdirectory();
			String fileSaveUUID = UUIDGenerator.getUUID();
			String fullPath = webRoot + sep + middlePath;
			buffer.append(middlePath).append(sep);
			 
			logger.debug("fullPath:" + fullPath);
			File rootDir = new File(webRoot); 
			File directory = null;
			if (!rootDir.exists()) {
				rootDir.mkdirs(); 
			} 
			directory = new File(rootDir, middlePath);
			if(!directory.exists() && !directory.mkdirs()){
				logger.error("创建文件存储路径失败【" + directory.getAbsolutePath() + "】");
			}  
			 
			StringBuffer fileLocation = new StringBuffer(webRoot);
			StringBuffer fileFullPath = new StringBuffer();
			fileLocation.append(middlePath); 
			fileLocation.append(sep); 
			
			fileFullPath.append(middlePath); 
			fileFullPath.append(sep); 
			String fileSaveName = "";
			int pos = fileName.lastIndexOf('.');
			if (pos == -1) {
				fileSaveName = fileSaveUUID;
			} else {
				fileSaveName = fileSaveUUID + fileName.substring(pos);
			}
			//buffer.append(fileSaveName);
			temp[2] = fileLocation.toString();
			fileLocation.append(fileSaveName);
			fileFullPath.append(fileSaveName);
			 
			logger.info("to store file: " + fileLocation);
			File file = new File(fileLocation.toString());
			if(!file.exists()){
				file.createNewFile();
			}
			logger.info("file created!");
			BufferedOutputStream bf = new BufferedOutputStream(
					new FileOutputStream(file));
			bf.write(fileContent);
			bf.close();
			temp[0] = buffer.toString();
			temp[1] = fileSaveName;
			return temp;
		}
	 @RequestMapping("/produce/downloadFile.do")   
		public   ModelAndView  downloadFile(HttpServletRequest request,
				HttpServletResponse response, ModelAndView mv) throws Exception {
				Map modelMap = new HashMap();
				String pid = request.getParameter("pid");
			    response.setCharacterEncoding("UTF-8");
				DnmsFile pobj = (DnmsFile)dataService.findByID(DnmsFile.class, new Long(pid));
				String filePath = GlobalParamCache.getInst().getParamByKey("dnmsabfile");
 				//String filePath = SystemUtil.getWebappRoot().toString();
 				//filePath = filePath.replace("\\", "/") + "/temp";
				String fileName = pobj.getFilename();
				String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
	 			logger.debug("ext:" + ext);

	 			String fileDbURL = pobj.getFilepath();
	 			logger.debug("fileDbURL:" + fileDbURL);
	 			filePath += fileDbURL;
 				logger.debug("test文件是否存在:" + new File(filePath).exists());

	 			filePath = filePath.replace("\\", "/");
	 			logger.debug("fileurl:" + filePath); 
				File file = new File(filePath);
				logger.debug("文件是否存在:" + file.exists());
		       
		        int fileLength = (int)file.length();
		        try{
		        	int                 length   = 0;
			        ServletOutputStream op       = response.getOutputStream();
			        ServletContext      context  = request.getSession().getServletContext();
			        String              mimetype = context.getMimeType( fileName );
			        byte[]   byteContents   =   new   byte[fileLength];   
			        FileInputStream fis   =   new   FileInputStream(file);   
			        int   retcd   =   fis.read(byteContents);   
			        fis.close();    
			        logger.debug("mimetype:" + mimetype);
			        response.setContentType(mimetype == null?"application/pdf":mimetype );
			        response.setContentLength( retcd );
			        response.setHeader( "Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"),"ISO-8859-1") + "\"" );

			        op.write(byteContents,0,retcd); 
			        op.close();
		            }catch(Exception e){
		            	e.printStackTrace();
		            }
	// 
	            return null;
		}
		
}
